package com.ruoyi.my.controller.util;

import com.ruoyi.common.core.domain.AjaxResult;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/util/hanzitopinyin")
public class HanZiToPinYin {

    /**
     * 汉字转拼音
     */
    @PreAuthorize("@ss.hasPermi('util:hanzitopinyin:convert')")
    @GetMapping("/convert/{hanZi}")
    public AjaxResult convert(@PathVariable String hanZi){
        if(hanZi == null || "".equals(hanZi)){
            return AjaxResult.success(201,"请输入需要转换的内容！");
        }
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        StringBuilder output = new StringBuilder();
        for (char c : hanZi.toCharArray()) {
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    output.append(pinyinArray[0]);
                } else {
                    output.append(c);
                }
            } catch (Exception e) {
                output.append(c);
            }
        }
        return AjaxResult.success(200,"转换成功！",output.toString().trim());
    }
}
